// Copyright 2011 Bryan McKelvey

/**
 * @fileoverview Main content script.
 * @author bryan.mckelvey@gmail.com (McKelvey Bryan)
 */

/**
 * Content script functions.
 * @namespace Content script functions.
 */
var Content = (function() {

  /**
   * Maximum number of checks against background script before giving up.
   * @type {number}
   * @final
   */
  var MAX_CHECKS = 20;

  /**
   * Milliseconds until the background script is checked again for games.
   * @type {number}
   * @final
   */
  var MS_TIL_CHECK_AGAIN = 1000;

  /**
   * Times the background script has been checked for games.
   * @type {number}
   * @final
   */
  var checkCount = 0;

  /**
   * Settings based on parsed local storage.
   * @type {Object.<boolean>}
   */
  var settings = {};

  /**
   * Writes links to streams into ESPN.com scoreboard.
   */
  function writeLinks() {
    chrome.extension.sendRequest({type: 'settings'}, function(response) {
      // Get pre-parsed settings from background script
      settings = response.settings;

      $('div.game-header').each(function() {
        var $gameHeader = $(this);
        var $div = $('<div>').addClass('mod-scorebox').addClass('flag').addClass('myp2pespn');
        var teams = [];
        $('a[href^=clubhouse]', $gameHeader).each(function() {
          var team = $(this).text();
          teams.push(team);
          
          // Duke => Dook
          if (team === 'Duke') {
            $(this).text('Dook');
          }
        });

        chrome.extension.sendRequest({type: 'games', teams: teams}, function(response) {
          // Sort links alphabetically by type, sending 'Other' to the back
          var links = response.links.sort(function(a, b) {
            return a.type.replace('Other', 'zzz') > b.type.replace('Other', 'zzz');
          });
          var $ul = $('<ul>');

          $.each(links, function(index, link) {
            if (link.type !== 'ESPN3' || settings.showEspn3) {
              // Build image source based on link type, setting to lower case and removing periods and whitespace
              // For example: Direct.tv => image/directtv.png
              var imageSource = chrome.extension.getURL('image/' + link.type.toLowerCase().replace(/\.|\s/g, '') + '.png');

              $ul.append(
                $('<li>').append(
                  $('<a>').attr({href: link.url, target: 'newtab', title: link.type + ': ' + link.url}).addClass(link.type).append(
                    $('<img>').attr('src', imageSource)
                  )
                )
              );
            }
          });
          
          // Add streaming links to scoreboard if they exist
          if ($ul.children().size() > 0) {
            $gameHeader.after($div.append($('<h2>').text('Stream:')).append($ul));
          }
        });
      });
    });
  }

  /**
   * Checks for games repeatedly until background script is ready or times out from too many iterations.
   */
  function checkForGames() {
    chrome.extension.sendRequest({type: 'done'}, function(response) {
      if (response.done) {
        writeLinks();
      } else {
        if (checkCount++ < MAX_CHECKS) {
          setTimeout(checkForGames, MS_TIL_CHECK_AGAIN);
        }
      }
    });
  }

  checkForGames();
}());